import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MBTIDAOImpl implements MBTIDAO {

    @Override
    public MBTI findByType(String type) {
        try (Connection connection = DBUtil.getConnection()) {
            // 修改SQL语句，去掉多余的数据库名前缀
            String sql = "SELECT * FROM MBTI WHERE Mtype =?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, type);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                MBTI mbti = new MBTI();
                mbti.setType(resultSet.getString("Mtype"));
                mbti.setFeature(resultSet.getString("Feature"));
                mbti.setFeatureType(resultSet.getString("Ftype"));
                return mbti;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<MBTI> getAllMBTITypes() {
        List<MBTI> mbtiList = new ArrayList<>();
        try (Connection connection = DBUtil.getConnection()) {
            // 修改SQL语句，去掉多余的数据库名前缀
            String sql = "SELECT * FROM MBTI";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                MBTI mbti = new MBTI();
                mbti.setType(resultSet.getString("Mtype"));
                mbti.setFeature(resultSet.getString("Feature"));
                mbti.setFeatureType(resultSet.getString("Ftype"));
                mbtiList.add(mbti);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return mbtiList;
    }

    @Override
    public void save(MBTI mbti) {
        try (Connection connection = DBUtil.getConnection()) {
            // 修改SQL语句，去掉多余的数据库名前缀
            String sql = "INSERT INTO MBTI (Mtype, Feature, Ftype) VALUES (?,?,?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, mbti.getType());
            preparedStatement.setString(2, mbti.getFture());
            preparedStatement.setString(3, mbti.getFType());
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}